<template>
  <el-dialog
    title="注册账号"
    :show-close="false"
    :visible.sync="isshow"
    ref="register"
    center
    width="600px"
  >
    <el-form ref="registerform" :model="registerform" :rules="rules" label-width="70px">
      <el-form-item label="头像" prop="usericon">
        <el-upload
          class="avatar-uploader"
          name="image"
          :action="baseUrl+'/uploads'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="registerform.usericon" :src="baseUrl+'/'+registerform.usericon" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input v-model="registerform.name" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerform.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="tel">
        <el-input v-model="registerform.tel" placeholder="请输入手机"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerform.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="imgcode">
        <el-row>
          <el-col :span="16">
            <el-input v-model="registerform.imgcode" placeholder="请输入图形码"></el-input>
          </el-col>
          <el-col :span="8">
            <div>
              <img class="imgcode" :src="imgcodesrc" @click="changecode" alt />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="telcode">
        <el-row>
          <el-col :span="16">
            <el-input v-model="registerform.telcode" placeholder="请输入验证码"></el-input>
          </el-col>
          <el-col :span="8">
            <el-button style="width:100%" :disabled="disable" @click="gettelcode">
              <span v-if="!disable">获取验证码</span>
              <span v-if="disable">剩余时间：{{secondscount}}秒</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelEvent">取 消</el-button>
      <el-button type="primary" @click="confirmEvent('registerform')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPhoneCodeApi, registerUserApi } from "@/api/register.js";
export default {
  created() {
    // this.imgcodesrc = this.baseUrl + "/captcha?type=sendsms";
  },
  data() {
    return {
      rules: {
        usericon: [{ required: true, message: "选择头像", trigger: "blur" }],
        name: [
          { required: true, message: "请输入", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "字符长度要在6-16位之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱地址"));
              }
            },
            trigger: "change",
          },
        ],
        tel: [
          { required: true, message: "请输入", trigger: "blur" },

          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱地址"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入", trigger: "blur" },

          {
            min: 6,
            max: 16,
            message: "字符长度要在6-16位之间",
            trigger: "blur",
          },
        ],
        imgcode: [
          { required: true, message: "请输入", trigger: "blur" },

          {
            min: 4,
            max: 4,
            message: "字符长度4位",
            trigger: "blur",
          },
        ],
        telcode: [
          { required: true, message: "请输入", trigger: "blur" },
          {
            min: 4,
            max: 4,
            message: "字符长度4",
            trigger: "blur",
          },
        ],
      },
      registerform: {
        usericon: "",
        name: "",
        email: "",
        tel: "",
        password: "",
        imgcode: "",
        telcode: "",
      },
      imgcodesrc: process.env.VUE_APP_URL + "/captcha?type=sendsms",
      baseUrl: process.env.VUE_APP_URL,
      isshow: false,
      imageUrl: "",
      disable: false,
      secondscount: 5,
    };
  },
  methods: {
    confirmEvent(registerform) {
      this.$refs[registerform].validate((result) => {
        if (result) {
          this.$message.success("验证通过");
          registerUserApi({
            username: this.registerform.name,
            phone: this.registerform.tel,
            email: this.registerform.email,
            avatar: this.registerform.usericon,
            password: this.registerform.password,
            rcode: this.registerform.telcode,
          }).then((res) => {
            //成功回调
            console.log(res);
            this.$message.success("注册成功");
          });
        } else {
          this.$message.error("验证失败");
        }
      });
      // this.isshow = false
    },
    cancelEvent() {
      this.$refs.registerform.resetFields();
      this.isshow = false;
    },
    changecode() {
      // console.log("请求新的验证码");
      this.imgcodesrc =
        this.baseUrl + "/captcha?type=sendsms&sahgsdhg=" + Math.random();
    },
    gettelcode() {
      let num = 0;
      this.$refs.registerform.validateField(
        ["tel", "imgcode"],
        (errorMessage) => {
          if (errorMessage == "") {
            //若错误信息为空则说明验证通过，num加一
            console.log(errorMessage);
            num++;
          }
        }
      );
      if (num == 2) {
        //两次均通过

        // this.$axios({
        //   url: "/sendsms",
        //   method: "post",
        //   data: {
        //     code: this.registerform.imgcode,
        //     phone: this.registerform.tel,
        //   },
        //   // withCredentials: true,
        //   // withCredentials: true,
        //   withCredentials: true,
        // })
        getPhoneCodeApi({
          code: this.registerform.imgcode,
          phone: this.registerform.tel,
        }).then((res) => {
          //成功回调
          console.log(res);
          console.log(this.registerform.imgcode, this.registerform.tel);
          this.$message.success("验证成功");
          this.$message.success(res.data.data.captcha + "");
        });
      } else {
        this.$message.error("验证失败");
      }
      //避免频繁点击，5秒/次
      // this.$refs.telcodebtn.style.disabled =true
      this.disable = true;
      this.secondscount = 5;
      let timeid = setInterval(() => {
        this.secondscount--;
        console.log(this.secondscount);
        if (this.secondscount == 0) {
          this.disable = false;
          clearInterval(timeid);
        }
      }, 1000);
    },
    handleAvatarSuccess(res) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      console.log(res);
      this.registerform.usericon = res.data.file_path;
      this.$refs.registerform.validateField(["usericon"]);
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;
      console.log(file);
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style>
.el-dialog__body {
  padding: 20px 5px;
}
.imgcode {
  /* text-align: center; */
  height: 40px;
}

.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>